package cn.shengchao.dubbo;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.shengchao.base.utils.SpringContextHolder;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeNodeInfo;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeNodeInfoService;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeDataStatusEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import cn.shengchao.examstart.user.acl.ports.repositories.IUserRepository;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import top.continew.admin.common.userContext.DistributeUserContextLoader;
import top.continew.admin.common.userContext.UserDistributeContext;

import java.util.List;
import java.util.Optional;


/**
 * Sa-Token 整合 Dubbo Provider端过滤器
 */
@Activate(group = {CommonConstants.PROVIDER}, order = -10000)
public class DistributeContextSettingDubboProviderFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        // 取出其他自定义附加数据
        // TenantContext tenantContext = invocation.getAttachment("tenantContext");
        UserDistributeContext userDistributeContext=getUserContext();
        if (userDistributeContext != null) {
            DistributeUserContextLoader.setUserContext(userDistributeContext);
        }
        // 开始调用
        return invoker.invoke(invocation);
    }

    private UserDistributeContext getUserContext() {
        try{
            Object createUser = StpUtil.getLoginId();
            System.out.println("分销角色上下文设置：用户登录id="+createUser);
            if (createUser != null) {
                IUserRepository userRepository=  SpringContextHolder.getBean(IUserRepository.class);
                DistributeNodeInfoService distributeNodeInfoService=  SpringContextHolder.getBean(DistributeNodeInfoService.class);
                List<DistributeNodeInfo> distributeNodeInfos = distributeNodeInfoService.list(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                        .eq(DistributeNodeInfo::getUserId, createUser)
                        .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus()));
                UserDistributeContext userDistributeContext = new UserDistributeContext();
                userDistributeContext.setUserId(createUser.toString());
                if (CollUtil.isNotEmpty(distributeNodeInfos)) {
                    Optional<DistributeNodeInfo> distributeNodeInfoSaleOptional = distributeNodeInfos.stream().filter(item-> DistributeTypeEnum.TYPE_SALE.getType()==(item.getDistributeType())).findFirst();
                    Optional<DistributeNodeInfo> distributeNodeInfoContentOptional = distributeNodeInfos.stream().filter(item-> DistributeTypeEnum.TYPE_CTPD.getType()==(item.getDistributeType())).findFirst();
                    distributeNodeInfoSaleOptional.ifPresent(distributeNodeInfo -> userDistributeContext.setDistributeSaleRoleCode(distributeNodeInfo.getDistributeRoleCode()));
                    distributeNodeInfoContentOptional.ifPresent(distributeNodeInfo -> userDistributeContext.setDistributeContentRoleCode(distributeNodeInfo.getDistributeRoleCode()));
                }
                return userDistributeContext;
            }
        } catch (Exception e) {
            System.out.println("分销角色上下文设置失败：用户登录id获取不到"+e.getMessage());
        }
        return null;
    }
}